package com.kaibo.roomdemo.net.http

import com.kaibo.roomdemo.App
import io.reactivex.schedulers.Schedulers
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

/**
 * @author Administrator
 * @date 2018/3/28 0028 上午 11:21
 * GitHub：
 * email：
 * description：
 */
object HttpClientUtil {

    private const val BASE_URL = "http://localhost:8080/"

    //缓存大小   20M
    private const val CACHE_SIZE = 1024 * 1024 * 20L

    //连接超时时间
    private const val CONNECT_TIMEOUT_TIME = 30L
    //读超时时间
    private const val READ_TIMEOUT_TIME = 30L
    //写超时时间
    private const val WRITE_TIMEOUT_TIME = 30L

    /**
     * 全局唯一一个 OkHttpClient  实例
     */
    val okHttpClient: OkHttpClient by lazy {
        OkHttpClient
                .Builder()
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                //失败重连
                .retryOnConnectionFailure(true)
                .connectTimeout(CONNECT_TIMEOUT_TIME, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT_TIME, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT_TIME, TimeUnit.SECONDS)
//                .cache(Cache(File("${App.getInstance().cacheDir.absolutePath}${File.separator}okHttpCaches"), CACHE_SIZE))
                .build()
    }

    /**
     * Retrofit   实例
     */
    val retrofit: Retrofit by lazy {
        Retrofit
                .Builder()
                .client(okHttpClient)
                .baseUrl(BASE_URL)
//                .addConverterFactory(FastJsonConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                //同步发出请求
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //使用okhttp的线程池
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
                //指定在RxJava的线程池发出请求
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build()
    }
}